package com.spzx.product.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.common.core.web.controller.BaseController;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.common.core.web.page.TableDataInfo;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.product.domain.ProductSpec;
import com.spzx.product.service.ProductSpecService;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 商品规格 前端控制器
 * </p>
 *
 * @author atguigu
 * @since 2025-04-28
 */
@RestController
@RequestMapping("/productSpec")
public class ProductSpecController extends BaseController {

    @Autowired
    ProductSpecService productSpecService;


    @Operation(summary = "商品规格分页查询")
    @GetMapping("/list")
    public TableDataInfo selectProductSpec(){
        List<ProductSpec> list=productSpecService.selectProductSpec();
        return getDataTable(list);
    }


    @Operation(summary = "新增商品规格")
    @PostMapping
    public AjaxResult addProductSpec(@RequestBody ProductSpec productSpec){

        productSpec.setCreateBy(SecurityUtils.getUsername());
        //判断当前商品规格名称和值是否存在
        LambdaQueryWrapper<ProductSpec> productSpecLambdaQueryWrapper = new LambdaQueryWrapper<>();
        productSpecLambdaQueryWrapper.eq(ProductSpec::getSpecName,productSpec.getSpecName());
        productSpecLambdaQueryWrapper.eq(ProductSpec::getSpecValue,productSpec.getSpecValue());
        productSpecLambdaQueryWrapper.eq(ProductSpec::getCategoryId,productSpec.getCategoryId());
        long count = productSpecService.count(productSpecLambdaQueryWrapper);
        if(count>0){
            throw  new RuntimeException("当前商品规格已存在");
        }

        productSpecService.save(productSpec);
        return AjaxResult.success();

    }


    @Operation(summary = "删除商品规格")
    @DeleteMapping("/{ids}")
    public AjaxResult deleteProductSpec(@PathVariable List<Long> ids){
        productSpecService.removeByIds(ids);
        return AjaxResult.success();
    }


    @Operation(summary = "根据分类id获取商品规格列表")
    @GetMapping("/productSpecList/{categoryId}")
    public AjaxResult selectProductSpecListByCategoryId(@PathVariable Long categoryId) {
        List<ProductSpec> list= productSpecService.selectProductSpecList(categoryId);
        return AjaxResult.success(list);
    }
}
